/*
 * @lc app=leetcode.cn id=1190 lang=typescript
 *
 * [1190] 反转每对括号间的子串
 */

// @lc code=start
function reverseParentheses(s: string): string {
  const size = s.length;
  const stack = [];
  const brackers = new Array(size).fill(0);
  // 记录每对括号的下标，将左右括号下标交换
  for (let i = 0; i < size; i++) {
    if (s[i] === '(') {
      stack.push(i);
    } else if (s[i] === ')') {
      let j = stack.pop();
      brackers[i] = j;
      brackers[j] = i;
    }
  }

  const strs = [];
  let idx = 0;
  let step = 1;
  // 遍历的时候出现括号，找到另一个对应括号的位置，然后反向遍历即可
  while (idx < size) {
    if (s[idx] === '(' || s[idx] === ')') {
      idx = brackers[idx];
      step = -step;
    } else {
      strs.push(s[idx]);
    }
    idx += step;
  }

  return strs.join('');
}
// @lc code=end
